import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, Avatar, Button, Modal, Form, Input, message, Tag, Statistic, List } from 'antd';
import { UserOutlined, EditOutlined, LogoutOutlined, SafetyOutlined, RightOutlined } from '@ant-design/icons';
import { getMe, updateProfile, changePassword, getStatistics } from '../../api/admin';

function Badge({ text, color = '#52c41a' }: { text: string; color?: string }) {
  return (
    <Tag color={color === '#1890ff' ? 'blue' : 'green'} style={{ borderRadius: 10 }}>
      {text}
    </Tag>
  );
}

function Stat({ icon, color, label, value }: { icon: string; color: string; label: string; value: string }) {
  return (
    <Card className="shadow-md" bordered={false}>
      <div className="flex items-center gap-3">
        <div 
          className="w-12 h-12 rounded-lg flex items-center justify-center text-xl"
          style={{ background: color, color: '#fff' }}
        >
          {icon}
        </div>
        <div>
          <div className="text-gray-500 text-sm">{label}</div>
          <div className="text-xl font-semibold">{value}</div>
        </div>
      </div>
    </Card>
  );
}

function RowItem({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex gap-3 mb-3">
      <div className="w-20 text-gray-500 text-sm">{label}</div>
      <div className="text-gray-800">{value}</div>
    </div>
  );
}

export default function AdminProfile() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { data: me, isLoading } = useQuery({ 
    queryKey: ['admin', 'me'], 
    queryFn: getMe,
    retry: false, // 不重试，失败直接使用mock
    // 注意：tryApiOrMock 已经处理了错误并降级到 mock，不会抛出异常
  });

  // 获取统计数据
  const { data: stats } = useQuery({
    queryKey: ['admin', 'statistics'],
    queryFn: getStatistics,
    retry: false,
  });
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  const updateProfileMutation = useMutation({
    mutationFn: updateProfile,
    onSuccess: (data) => {
      queryClient.setQueryData(['admin', 'me'], data);
      message.success('个人信息更新成功');
      setIsEditModalOpen(false);
      form.resetFields();
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  const changePasswordMutation = useMutation({
    mutationFn: changePassword,
    onSuccess: () => {
      message.success('密码修改成功');
      setIsPasswordModalOpen(false);
      passwordForm.resetFields();
    },
    onError: (error: any) => {
      message.error(error.message || '密码修改失败，请检查旧密码是否正确');
    },
  });

  const handleEdit = () => {
    if (me) {
      form.setFieldsValue({
        name: me.name,
        email: me.email || '',
        phone: me.phone || '',
      });
      setIsEditModalOpen(true);
    } else {
      message.warning('个人信息加载中，请稍候');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // 后端UpdateAdminRequest只支持：name
      const updateData = {
        name: values.name,
      };
      updateProfileMutation.mutate(updateData);
    } catch (error) {
      console.error('表单验证失败:', error);
      message.error('请检查表单输入是否正确');
    }
  };

  const handleLogout = () => {
    setIsLoggingOut(true);
    localStorage.removeItem('token');
    localStorage.removeItem('role');
    localStorage.removeItem('dev_mode');
    navigate('/login');
  };

  return (
    <div className="p-4 pb-24">
      <div className="text-2xl font-semibold mb-4">个人信息</div>

      <Card className="shadow-md mb-4" loading={isLoading}>
        <div className="flex items-center gap-4 mb-4">
          <Avatar 
            size={72} 
            icon={<UserOutlined />} 
            className="flex-shrink-0"
            style={{ 
              background: '#f2f6ff',
              color: '#1890ff',
              fontSize: '32px'
            }} 
          />
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <div className="text-xl font-semibold">{me?.name || '管理员'}</div>
              <Badge text="系统管理员" color="#1890ff" />
            </div>
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={handleEdit}
              style={{ 
                background: '#f5f7ff', 
                color: '#3e5bdb', 
                border: '1px solid #e3e7ff'
              }}
            >
              编辑资料
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <RowItem label="姓名" value={me?.name || '-'} />
            <RowItem label="邮箱" value={me?.email || '-'} />
            <RowItem label="最后登录" value={me?.lastLogin || '-'} />
          </div>
          <div>
            <RowItem label="工号" value={me?.account || '-'} />
            <RowItem label="电话" value={me?.phone || '-'} />
            <div className="flex gap-3 mb-3">
              <div className="w-20 text-gray-500 text-sm">账号状态</div>
              <Badge text="正常" />
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
        <Stat icon="👥" color="#1890ff" label="总用户数" value={stats ? stats.totalUsers.toLocaleString() : '0'} />
        <Stat icon="📚" color="#52c41a" label="课程总数" value={stats ? stats.totalCourses.toLocaleString() : '0'} />
        <Stat icon="📝" color="#faad14" label="待审核申请" value={stats ? stats.pendingApplications.toLocaleString() : '0'} />
      </div>

      {/* 安全设置 */}
      <Card 
        title={<span className="text-lg font-semibold text-gray-800">安全设置</span>}
        className="shadow-md"
        bordered={false}
      >
        <List
          itemLayout="horizontal"
          dataSource={[
            { 
              icon: <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                <SafetyOutlined className="text-blue-500 text-lg" />
              </div>, 
              title: '修改密码', 
              desc: '上次修改：30天前',
              onClick: () => {
                setIsPasswordModalOpen(true);
                passwordForm.resetFields();
              } 
            },
            { 
              icon: <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                <LogoutOutlined className="text-red-500 text-lg" />
              </div>, 
              title: isLoggingOut ? '退出中...' : '退出登录', 
              desc: '',
              danger: true, 
              onClick: handleLogout,
              disabled: isLoggingOut
            },
          ]}
          renderItem={(item) => (
            <List.Item 
              onClick={item.disabled ? undefined : item.onClick} 
              className={`${item.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-gray-50'} rounded-lg px-3 transition-colors`}
            >
              <List.Item.Meta 
                avatar={item.icon} 
                title={
                  <span className={`text-base ${item.danger ? 'text-red-500 font-medium' : 'text-gray-800 font-medium'}`}>
                    {item.title}
                  </span>
                }
                description={item.desc && (
                  <span className="text-xs text-gray-400 mt-1 block">{item.desc}</span>
                )}
              />
              {!item.disabled && <RightOutlined className="text-gray-400" />}
            </List.Item>
          )}
        />
      </Card>

      {/* 编辑资料Modal */}
      <Modal
        title="编辑资料"
        open={isEditModalOpen}
        onCancel={() => {
          setIsEditModalOpen(false);
          form.resetFields();
        }}
        onOk={handleSubmit}
        confirmLoading={updateProfileMutation.isPending}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          className="mt-4"
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱（可选）" />
          </Form.Item>

          <Form.Item
            label="联系电话"
            name="phone"
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input placeholder="请输入联系电话（可选）" />
          </Form.Item>

          <div className="text-sm text-gray-500 mt-4">
            <div className="mb-2">工号：{me?.account || '-'}</div>
            <div className="text-xs">工号不可修改</div>
          </div>
        </Form>
      </Modal>

      {/* 修改密码Modal */}
      <Modal
        title="修改密码"
        open={isPasswordModalOpen}
        onCancel={() => {
          setIsPasswordModalOpen(false);
          passwordForm.resetFields();
        }}
        onOk={() => {
          passwordForm.submit();
        }}
        confirmLoading={changePasswordMutation.isPending}
        okText="确认修改"
        cancelText="取消"
        width={500}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          className="mt-4"
          onFinish={(values) => {
            changePasswordMutation.mutate({
              oldPassword: values.oldPassword,
              newPassword: values.newPassword,
            });
          }}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password placeholder="请输入当前密码" />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少为6位' },
            ]}
          >
            <Input.Password placeholder="请输入新密码（至少6位）" />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

